import router from "@/router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { asyncRoutes } from "@/router";
import store from "@/store";

/**
 *前置守卫
 *
 */
let isTo = true;
const whiteList = ["/login", "/404"];
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  if (store.getters.token) {
    // console.log(store.getters.token);
    // 存在token
    if (to.path === "/login") {
      // 跳转到主页
      next("/"); // 中转到主页
      // next（地址）并没有执行后置守卫
      nprogress.done();
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch("user/getUserInfo");
        console.log(roles);
        const filterRoutes = asyncRoutes.filter((item) => {
          // return true/false
          return roles.menus.includes(item.name);
        }); // 筛选后的路由
        console.log(filterRoutes);
        store.commit("user/setRoutes", [
          ...filterRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]);
        router.addRoutes([
          ...filterRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]); // 添加动态路由信息到路由表
        if (filterRoutes.some((route) => to.matched.flat().includes(route))) {
          next(to.path); // 如果目标路由在授权路由内，允许访问
        } else {
          next("/"); // 否则重定向到404
        }
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login"); // 中转到登录页
      nprogress.done();
    }
  }
});

/** *
 * 后置守卫
 * **/
router.afterEach(() => {
  // console.log("123");
  nprogress.done();
});
